class watcher{
    constructor(vm,expr,cb){
        this.vm = vm;
        this.expr = expr;
        this.cb = cb;
        //先把旧值保存起来；
        this.oldVal = this.getOldValue()
    }
    getOldValue(){
        Dep.target = this;
        const oldval = compileUtil.getVal(this.expr,this.vm)
        Dep.target = null
        return oldval
    }

    update(){
        const newVal = compileUtil.getVal(this.expr,this.vm)
        if(newVal !== this.oldval){
            this.cb(newVal)
        }
    }
}

class Dep{
    constructor(){
        this.subs = []
    }
    //收集观察者
    addSub(watcher){
        console.log("收集了观察者")
        this.subs.push(watcher)
    }
    //通知观察者去更新
    notify(){
        console.log("通知了观察者",this.subs)
        this.subs.forEach(w=>w.update())
    }

}
class Observer {
    constructor(data){
        this.observer(data)
    }
    observer(data){
        if(data && typeof data == 'object'){
            Object.keys(data).forEach(key =>{
                this.defineReactive(data,key,data[key])
            })
        }
    }

    defineReactive(data,key,value){
        //递归遍历
        this.observer(value);
        const dep = new Dep();
        Object.defineProperty(data,key,{
            enumerable:true,
            configurable:false,
            get(){
               // 初始化
                // 订阅数据变化是，往dep中增加观察者；
                console.log("9999999999")
                console.log(Dep.target)
                
                Dep.target && dep.addSub(Dep.target)
                return value
            },
            set:(newVal) =>{
                this.observer(newVal)
                if(newVal !== value){
                    value = newVal;
                }
                //告诉Dep通知变化
                dep.notify();
            }
        })
    }
}